#!/usr/bin/env php
<?php
require_once('../config.php');
$mysqli = new mysqli($db['host'], $db['user'], $db['pass'], $db['db']);
$mysqli->set_charset($db['enc']);

require_once('/Users/dimus/Sites/taxamatch/api/config.php');
require_once('/Users/dimus/Sites/taxamatch/api/classes/class.taxamatch.php');
require_once('/Users/dimus/Sites/taxamatch/api/classes/class.gni_splitter.php');
require_once('gni_matcher.php');

function reconcile($limit, $db, $db_shared){ 
  $batch_size = Database::BATCH_SIZE;
  $data_file = "results/".$limit."_of".$batch_size.".txt";
  $f = fopen($data_file, 'w') or die("Cannot open $data_file");
  $gm = new GniMatcher();

  $res = $db->query("SELECT id, word1, word2 FROM extended_canonical_forms WHERE number_of_words=2 order by word1, word2 limit $limit, $batch_size");
  
  echo "$limit limit rows to process: ". $res->num_rows."\n";
  $count = 0;
  while($record = $res->fetch_object()) {
    $canonical_id = $record->id;
    $genus = $record->word1;
    $species = $record->word2;
    $count += 1;
    if ($count % 100 == 0) print "$limit: $count "; 
    if ($genus == '' || $genus == null) continue;
    fwrite($f, "#Canonical: $genus $species\n");
    $matched_res = $db->query("select id, matched_data from genus_words where normalized = '$genus'");
    $matched_res = $matched_res ? $matched_res->fetch_row() : array(null, null);
    $genus_id = $matched_res[0];
    $genus_match = $matched_res[1];
    if ($genus_id) {
      $genus_match = $genus_match ? json_decode($genus_match, true) : $gm->match_genera($genus, $genus_id);
      //print_r($genus_match);
      $canonical_ids = $gm->match_names($species, $genus_match, $canonical_id);
      $matchers = $gm->match_name_strings($canonical_id, $canonical_ids);
      foreach($matchers as $match) {
        list($id1,$id2,$name1,$name2,$edit_distance,$auth_score) = $match;
        //print_r($match);
        $distance_score = 0;
        fwrite($f, "$edit_distance\t$auth_score\t$count\t$name1\t$name2\n\n");
        $query = "insert IGNORE into taxamatchers (name_string_id1, name_string_id2, edit_distance, taxamatch_score, author_score, matched, algorithmic, created_at, updated_at) values ($id1, $id2, $edit_distance, $distance_score, $auth_score, 1, 1, now(), now())";
        $db_shared->query($query);
      }
    } else {
      fwrite($f, "Did not find $genus in genus_word table\n\n");
    }
  }
  fclose($f) or die("Cannot close file $data_file\n");
  $db_shared->query("insert into taxamatch_statuses (finished_task) values ('$limit')");
  print "\n";
}


$db = Database::instance()->cursor;
$db_shared = Database::instance()->shared_cursor;

if (isset($argv[1]) && $argv[1] == '-c') {
  print "cluster mode\n";
} else if (isset($argv[1]) && $argv[1] == '-l') {
  $limit = (isset($argv[2]) && preg_match("/^\d+$/", $argv[2])) ? $argv[2] : 0;
  print "executing in parameter mode\n";
  reconcile($limit, $db, $db_shared);
} else {
  print "Usage:\n\nCluster mode:\n". $argv[0] ." -c\n\nParameter mode\n". $argv[0] ." -l nnnn\n\n"; 
}

